package com.summer.bilibili.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.summer.bilibili.controller.BaseController;
import com.summer.bilibili.domain.enums.AuditStatus;
import com.summer.bilibili.domain.enums.AuditType;
import com.summer.bilibili.domain.system.SysAudit;
import com.summer.bilibili.domain.video.Video;
import com.summer.bilibili.domain.video.VideoPart;
import com.summer.bilibili.domain.vo.VideoAudit;
import com.summer.bilibili.mapper.SysAuditMapper;
import com.summer.bilibili.service.VideoAuditService;
import com.summer.bilibili.service.VideoPartService;
import com.summer.bilibili.service.VideoService;
import com.summer.bilibili.vo.VideoPartVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
@RequiredArgsConstructor
public class VideoAuditServiceImpl extends BaseServiceImpl<SysAudit, SysAuditMapper > implements VideoAuditService {
    private final VideoService videoService;
    private final VideoPartService videoPartService;

    @Override
    public IPage< VideoAudit > search() {
        return wrapper()
                .selectAll( Video.class)
                .selectCount( SysAudit::getId, VideoAudit::getAuditCount)
                .innerJoin( VideoPart.class, VideoPart::getId, SysAudit::getTargetId)
                .innerJoin(Video.class, Video::getId, VideoPart::getVideoId)
                .eq(SysAudit::getAuditType, AuditType.VIDEO_PART)
                .eq(SysAudit::getAuditStatus, AuditStatus.UNKNOWN)
                .groupBy(VideoPart::getVideoId)
                .page( BaseController.createPage(), VideoAudit.class);
    }

    @Override
    public VideoAudit getVideoAudit(Long videoId) {
        VideoAudit videoAudit = videoService.getById(videoId, VideoAudit.class);
        if (videoAudit == null) {
            return null;
        }
        List< VideoPartVo > parts = videoPartService.wrapper()
                .selectAssociation(SysAudit.class, VideoPartVo::getSysAudit)
                .innerJoin(SysAudit.class, SysAudit::getTargetId, VideoPart::getId)
                .eq(VideoPart::getVideoId, videoId)
                .eq(SysAudit::getAuditStatus, AuditStatus.UNKNOWN)
                .list(VideoPartVo.class);
        videoAudit.setParts(parts);
        videoAudit.setAuditCount(parts.size());
        return videoAudit;
    }
}
